// db.rs

use rusqlite::{params, Connection, Result};
use crate::handlers::DeviceParams;

pub struct Database {
    conn: Connection,
}

impl Database {
    pub fn new(path: &str) -> Result<Self> {
        let conn = Connection::open(path)?;
        conn.execute(
            "CREATE TABLE IF NOT EXISTS devices (
                dev_eui TEXT PRIMARY KEY,
                app_eui TEXT NOT NULL,
                app_key TEXT NOT NULL,
                dev_nonce TEXT NOT NULL,
                dev_addr TEXT NOT NULL,
                nwk_skey TEXT NOT NULL,
                app_skey TEXT NOT NULL
            )",
            [],
        )?;
        Ok(Self { conn })
    }

    pub fn add_device(&self, device: DeviceParams) -> Result<()> {
        self.conn.execute(
            "INSERT INTO devices (dev_eui, app_eui, app_key, dev_nonce, dev_addr, nwk_skey, app_skey) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
            params![
                device.dev_eui,
                device.app_eui,
                device.app_key,
                device.dev_nonce,
                device.dev_addr,
                device.nwk_skey,
                device.app_skey,
            ],
        )?;
        Ok(())
    }

    pub fn get_device(&self, dev_eui: &str) -> Result<Option<DeviceParams>> {
        let mut stmt = self.conn.prepare("SELECT dev_eui, app_eui, app_key, dev_nonce, dev_addr, nwk_skey, app_skey FROM devices WHERE dev_eui = ?1")?;
        let mut rows = stmt.query(params![dev_eui])?;

        if let Some(row) = rows.next()? {
            Ok(Some(DeviceParams {
                dev_eui: row.get(0)?,
                app_eui: row.get(1)?,
                app_key: row.get(2)?,
                dev_nonce: row.get(3)?,
                dev_addr: row.get(4)?,
                nwk_skey: row.get(5)?,
                app_skey: row.get(6)?,
                join_nonce:row.get(7)?,
            }))
        } else {
            Ok(None)
        }
    }
}
